/**
 * AI日记页面
 * 
 * 功能：
 * 1. 记录日常流水账
 * 2. 查看历史日记
 * 3. 生成AI每日总结
 */

import { useEffect, useState } from 'react';
import { Card, CardHeader, CardTitle, CardDescription, CardAction, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Calendar } from '@/components/ui/calendar';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Loader2, RefreshCw, AlertCircle, Plus, Edit, Trash2, CalendarIcon, Sparkles } from 'lucide-react';
import { get, post, put, del } from '@/lib/apiClient';
import { getProviders, callAI, type ChatMessage } from '@/lib/ai-config';

// 日记条目接口
interface DiaryEntry {
  id: number;
  content: string;
  mood?: string;
  weather?: string;
  tags: string[];
  created_at: string;
  updated_at: string;
}

// AI总结接口
interface DiarySummary {
  id: number;
  date: string;
  summary: string;
  highlights: string[];
  mood_analysis: string;
  created_at: string;
  updated_at: string;
}

// API响应接口
interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
  pagination?: {
    page: number;
    per_page: number;
    total: number;
    pages: number;
    has_next: boolean;
    has_prev: boolean;
  };
}

export default function AiDairy() {
  // ==================== 辅助函数 ====================
  // 将日期格式化为 YYYY-MM-DD 格式（使用本地时区）
  const formatDateToLocalString = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  // 将UTC时间字符串转换为本地时间显示
  const formatDateTimeToLocal = (utcTimeString: string): string => {
    if (!utcTimeString) return '';
    const utcDate = new Date(utcTimeString);
    return utcDate.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      timeZone: 'Asia/Shanghai'
    });
  };

  // ==================== 状态管理 ====================
  const [entries, setEntries] = useState<DiaryEntry[]>([]);
  const [summaries, setSummaries] = useState<DiarySummary[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // 日历和日期状态 - 初始化时设置为今天
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(() => {
    const today = new Date();
    // 确保使用本地时区
    return new Date(today.getFullYear(), today.getMonth(), today.getDate());
  });
  const [month, setMonth] = useState<Date | undefined>(() => {
    const today = new Date();
    return new Date(today.getFullYear(), today.getMonth(), 1);
  });
  
  // 新建日记状态
  const [showNewEntry, setShowNewEntry] = useState(false);
  const [newEntry, setNewEntry] = useState({
    content: '',
    mood: '',
    weather: '',
    tags: [] as string[]
  });
  
  // 编辑状态
  const [editingEntry, setEditingEntry] = useState<DiaryEntry | null>(null);
  
  // 总结生成状态
  const [generatingSummary, setGeneratingSummary] = useState(false);

  // ==================== 数据加载 ====================
  // 根据选中日期加载日记条目
  const loadEntriesForDate = async (date: Date | undefined) => {
    if (!date) {
      setEntries([]);
      return;
    }
    
    try {
      const dateStr = formatDateToLocalString(date);
      const response = await get<ApiResponse<DiaryEntry[]>>(`/ai_dairy/entries?date=${dateStr}`);
      if (response.success) {
        setEntries(response.data);
      }
    } catch (err) {
      console.error('Failed to load entries:', err);
    }
  };

  // 根据选中日期加载AI总结
  const loadSummariesForDate = async (date: Date | undefined) => {
    if (!date) {
      setSummaries([]);
      return;
    }
    
    try {
      const dateStr = formatDateToLocalString(date);
      const response = await get<ApiResponse<DiarySummary[]>>(`/ai_dairy/summaries?date=${dateStr}`);
      if (response.success) {
        setSummaries(response.data);
      }
    } catch (err) {
      console.error('Failed to load summaries:', err);
    }
  };

  // 加载当前选中日期的数据
  const loadDataForSelectedDate = async () => {
    try {
      setLoading(true);
      setError(null);
      await Promise.all([loadEntriesForDate(selectedDate), loadSummariesForDate(selectedDate)]);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载数据失败');
      console.error('Failed to load data:', err);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载和日期变化时重新加载
  useEffect(() => {
    loadDataForSelectedDate();
  }, [selectedDate]); // eslint-disable-line react-hooks/exhaustive-deps

  // ==================== 操作函数 ====================
  
  // 创建日记条目
  const handleCreateEntry = async () => {
    try {
      if (!newEntry.content.trim()) {
        alert('请输入日记内容');
        return;
      }

      const response = await post<ApiResponse<DiaryEntry>>(
        '/ai_dairy/entries',
        newEntry
      );
      
      if (response.success) {
        setNewEntry({ content: '', mood: '', weather: '', tags: [] });
        setShowNewEntry(false);
        await loadEntriesForDate(selectedDate);
      }
    } catch (err) {
      console.error('Failed to create entry:', err);
      alert(err instanceof Error ? err.message : '创建失败');
    }
  };

  // 更新日记条目
  const handleUpdateEntry = async (entry: DiaryEntry) => {
    try {
      const response = await put<ApiResponse<DiaryEntry>>(
        `/ai_dairy/entries/${entry.id}`,
        {
          content: entry.content,
          mood: entry.mood,
          weather: entry.weather,
          tags: entry.tags
        }
      );
      
      if (response.success) {
        setEditingEntry(null);
        await loadEntriesForDate(selectedDate);
      }
    } catch (err) {
      console.error('Failed to update entry:', err);
      alert(err instanceof Error ? err.message : '更新失败');
    }
  };

  // 删除日记条目
  const handleDeleteEntry = async (id: number) => {
    if (!confirm('确定要删除这条日记吗？')) return;
    
    try {
      const response = await del<ApiResponse<null>>(
        `/ai_dairy/entries/${id}`
      );
      
      if (response.success) {
        await loadEntriesForDate(selectedDate);
      }
    } catch (err) {
      console.error('Failed to delete entry:', err);
      alert(err instanceof Error ? err.message : '删除失败');
    }
  };

  // 生成AI总结
  const handleGenerateSummary = async () => {
    if (!selectedDate) {
      alert('请选择日期');
      return;
    }
    
    try {
      setGeneratingSummary(true);
      
      // 获取启用的AI提供商
      const providers = getProviders();
      const enabledProvider = providers.find(p => p.enabled && p.apiKey);
      
      if (!enabledProvider) {
        alert('请先在系统设置中配置并启用AI服务');
        return;
      }
      
      // 检查当前日期是否有日记
      if (entries.length === 0) {
        alert('该日期没有日记条目');
        return;
      }
      
      // 构建AI提示词
      const diaryContent = entries
        .map(entry => {
          const localTime = new Date(entry.created_at).toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit',
            timeZone: 'Asia/Shanghai'
          });
          return `${localTime} - ${entry.content}`;
        })
        .join('\n');
      
      const prompt = `请根据以下日记内容，生成一份温馨的每日总结：

日记内容：
${diaryContent}

请生成：
1. 一份简洁的每日总结（200-300字）
2. 3-5个今日亮点事件
3. 心情分析（基于日记内容分析情绪变化）

请以JSON格式返回：
{
    "summary": "每日总结内容",
    "highlights": ["亮点1", "亮点2", "亮点3"],
    "mood_analysis": "心情分析内容"
}`;

      // 调用AI API
      const messages: ChatMessage[] = [
        {
          id: '1',
          role: 'user',
          content: prompt,
          timestamp: Date.now()
        }
      ];
      
      const config = {
        temperature: 0.7,
        maxTokens: 1000,
        topP: 1,
        stream: false
      };
      
      // 使用第一个可用的模型
      const model = enabledProvider.models[0];
      const aiResponse = await callAI(enabledProvider, model, messages, config);
      
      try {
        // 解析AI返回的JSON
        const aiData = JSON.parse(aiResponse);
        
        // 创建总结记录
        const summaryData = {
          date: formatDateToLocalString(selectedDate),
          summary: aiData.summary || '',
          highlights: aiData.highlights || [],
          mood_analysis: aiData.mood_analysis || ''
        };
        
        const response = await post<ApiResponse<DiarySummary>>(
          '/ai_dairy/summaries',
          summaryData
        );
        
        if (response.success) {
          await loadSummariesForDate(selectedDate);
          alert('AI总结生成成功！');
        }
      } catch (jsonError) {
        console.error('AI返回格式错误:', jsonError);
        alert('AI返回格式错误，请重试');
      }
      
    } catch (err) {
      console.error('Failed to generate summary:', err);
      alert(err instanceof Error ? err.message : '生成总结失败');
    } finally {
      setGeneratingSummary(false);
    }
  };

  // ==================== 渲染逻辑 ====================

  // 加载状态
  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  // 错误状态
  if (error) {
    return (
      <div className="flex flex-col items-center justify-center h-96 gap-4">
        <AlertCircle className="h-12 w-12 text-destructive" />
        <p className="text-destructive">{error}</p>
        <Button onClick={loadDataForSelectedDate}>重试</Button>
      </div>
    );
  }

  // 主内容
  return (
    <div className="space-y-6 h-full">
      {/* ========== 页面标题 ========== */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">AI日记</h1>
          <p className="text-muted-foreground mt-2">
            {selectedDate && `${selectedDate.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })} 的记录`}
          </p>
        </div>
        
        {/* 操作按钮 */}
        <div className="flex gap-2">
          <Button onClick={loadDataForSelectedDate} variant="outline" size="sm">
            <RefreshCw className="h-4 w-4 mr-2" />
            刷新
          </Button>
          <Button onClick={() => setShowNewEntry(true)} size="sm">
            <Plus className="h-4 w-4 mr-2" />
            写日记
          </Button>
        </div>
      </div>

      {/* ========== 新建日记对话框（悬浮） ========== */}
      {showNewEntry && (
        <Card className="p-6 mb-6">
          <h3 className="text-lg font-semibold mb-4">写新日记</h3>
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium mb-2 block">日记内容 *</label>
              <textarea
                className="w-full p-3 border rounded-lg resize-none"
                rows={4}
                placeholder="记录今天发生的事情..."
                value={newEntry.content}
                onChange={(e) => setNewEntry({ ...newEntry, content: e.target.value })}
              />
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="text-sm font-medium mb-2 block">心情</label>
                <select
                  className="w-full p-2 border rounded-lg"
                  value={newEntry.mood}
                  onChange={(e) => setNewEntry({ ...newEntry, mood: e.target.value })}
                >
                  <option value="">选择心情</option>
                  <option value="开心">😊 开心</option>
                  <option value="平静">😌 平静</option>
                  <option value="兴奋">🤩 兴奋</option>
                  <option value="疲惫">😴 疲惫</option>
                  <option value="难过">😢 难过</option>
                  <option value="焦虑">😰 焦虑</option>
                </select>
              </div>
              
              <div>
                <label className="text-sm font-medium mb-2 block">天气</label>
                <select
                  className="w-full p-2 border rounded-lg"
                  value={newEntry.weather}
                  onChange={(e) => setNewEntry({ ...newEntry, weather: e.target.value })}
                >
                  <option value="">选择天气</option>
                  <option value="晴天">☀️ 晴天</option>
                  <option value="多云">⛅ 多云</option>
                  <option value="雨天">🌧️ 雨天</option>
                  <option value="阴天">☁️ 阴天</option>
                  <option value="雪天">❄️ 雪天</option>
                </select>
              </div>
            </div>
            
            <div className="flex gap-2">
              <Button onClick={handleCreateEntry}>保存日记</Button>
              <Button variant="outline" onClick={() => setShowNewEntry(false)}>取消</Button>
            </div>
          </div>
        </Card>
      )}

      {/* ========== 左右布局：左侧日历，右侧标签页 ========== */}
      <div className="grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-6">
        {/* 左侧：日历 */}
        <div className="flex justify-center lg:justify-start">
          <Card>
            <CardHeader>
              <CardTitle>选择日期</CardTitle>
              <CardDescription>点击日期查看当天的日记</CardDescription>
              <CardAction>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => {
                    const today = new Date();
                    // 确保使用本地时区
                    const todayDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
                    const todayMonth = new Date(today.getFullYear(), today.getMonth(), 1);
                    setMonth(todayMonth);
                    setSelectedDate(todayDate);
                  }}
                >
                  今天
                </Button>
              </CardAction>
            </CardHeader>
            <CardContent>
              <Calendar
                mode="single"
                month={month}
                onMonthChange={setMonth}
                selected={selectedDate}
                onSelect={(date) => {
                  // 确保日期选择时使用本地时区
                  if (date) {
                    const localDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
                    setSelectedDate(localDate);
                  } else {
                    setSelectedDate(undefined);
                  }
                }}
                className="bg-transparent p-0"
              />
            </CardContent>
          </Card>
        </div>

        {/* 右侧：标签页（日记列表和AI总结） */}
        <div className="h-[calc(100vh-16rem)]">
          <Tabs defaultValue="entries" className="h-full flex flex-col">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="entries">
                <CalendarIcon className="h-4 w-4 mr-2" />
                日记列表
              </TabsTrigger>
              <TabsTrigger value="summaries">
                <Sparkles className="h-4 w-4 mr-2" />
                AI总结
              </TabsTrigger>
            </TabsList>
            
            {/* 日记列表标签页 */}
            <TabsContent value="entries" className="flex-1 overflow-hidden">
              <div className="h-full overflow-y-auto pr-2">
                {entries.length === 0 ? (
                  <div className="text-center py-12 text-muted-foreground">
                    <CalendarIcon className="h-12 w-12 mx-auto mb-4 opacity-50" />
                    <p>该日期还没有日记，开始记录你的生活吧！</p>
                    <Button onClick={() => setShowNewEntry(true)} variant="outline" className="mt-4">
                      写日记
                    </Button>
                  </div>
                ) : (
                  <div className="space-y-4">
                    {entries.map((entry) => (
                      <div key={entry.id}>
                        {editingEntry && editingEntry.id === entry.id ? (
                          // 编辑表单
                          <Card className="p-4">
                            <h4 className="font-medium mb-3">编辑日记</h4>
                            <div className="space-y-3">
                              <div>
                                <label className="text-sm font-medium mb-1 block">日记内容</label>
                                <textarea
                                  className="w-full p-2 border rounded-lg resize-none"
                                  rows={3}
                                  value={editingEntry.content}
                                  onChange={(e) => setEditingEntry({ ...editingEntry, content: e.target.value })}
                                />
                              </div>
                              
                              <div className="grid grid-cols-2 gap-3">
                                <div>
                                  <label className="text-sm font-medium mb-1 block">心情</label>
                                  <select
                                    className="w-full p-2 border rounded-lg"
                                    value={editingEntry.mood || ''}
                                    onChange={(e) => setEditingEntry({ ...editingEntry, mood: e.target.value })}
                                  >
                                    <option value="">选择心情</option>
                                    <option value="开心">😊 开心</option>
                                    <option value="平静">😌 平静</option>
                                    <option value="兴奋">🤩 兴奋</option>
                                    <option value="疲惫">😴 疲惫</option>
                                    <option value="难过">😢 难过</option>
                                    <option value="焦虑">😰 焦虑</option>
                                  </select>
                                </div>
                                
                                <div>
                                  <label className="text-sm font-medium mb-1 block">天气</label>
                                  <select
                                    className="w-full p-2 border rounded-lg"
                                    value={editingEntry.weather || ''}
                                    onChange={(e) => setEditingEntry({ ...editingEntry, weather: e.target.value })}
                                  >
                                    <option value="">选择天气</option>
                                    <option value="晴天">☀️ 晴天</option>
                                    <option value="多云">⛅ 多云</option>
                                    <option value="雨天">🌧️ 雨天</option>
                                    <option value="阴天">☁️ 阴天</option>
                                    <option value="雪天">❄️ 雪天</option>
                                  </select>
                                </div>
                              </div>
                              
                              <div className="flex gap-2">
                                <Button onClick={() => handleUpdateEntry(editingEntry)} size="sm">
                                  保存
                                </Button>
                                <Button 
                                  variant="outline" 
                                  size="sm"
                                  onClick={() => setEditingEntry(null)}
                                >
                                  取消
                                </Button>
                              </div>
                            </div>
                          </Card>
                        ) : (
                          // 正常显示
                          <div className="p-4 border rounded-lg hover:bg-accent transition-colors">
                            <div className="flex items-start justify-between">
                              <div className="flex-1">
                                <div className="flex items-center gap-2 mb-2">
                                  <span className="text-sm text-muted-foreground">
                                    {formatDateTimeToLocal(entry.created_at)}
                                  </span>
                                  {entry.mood && (
                                    <Badge variant="secondary">{entry.mood}</Badge>
                                  )}
                                  {entry.weather && (
                                    <Badge variant="outline">{entry.weather}</Badge>
                                  )}
                                </div>
                                <p className="text-gray-800 whitespace-pre-wrap">{entry.content}</p>
                                {entry.tags.length > 0 && (
                                  <div className="flex gap-1 mt-2">
                                    {entry.tags.map((tag, index) => (
                                      <Badge key={index} variant="secondary" className="text-xs">
                                        #{tag}
                                      </Badge>
                                    ))}
                                  </div>
                                )}
                              </div>
                              
                              <div className="flex gap-2 ml-4">
                                <Button
                                  onClick={() => setEditingEntry(entry)}
                                  variant="outline"
                                  size="sm"
                                >
                                  <Edit className="h-4 w-4" />
                                </Button>
                                <Button
                                  onClick={() => handleDeleteEntry(entry.id)}
                                  variant="destructive"
                                  size="sm"
                                >
                                  <Trash2 className="h-4 w-4" />
                                </Button>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </TabsContent>

            {/* AI总结标签页 */}
            <TabsContent value="summaries" className="flex-1 overflow-hidden">
              <div className="h-full overflow-y-auto pr-2 space-y-6">
                {/* 生成总结按钮 */}
                <div className="flex justify-between items-center">
                  <p className="text-sm text-muted-foreground">
                    {selectedDate && `${selectedDate.toLocaleDateString('zh-CN')} 的AI总结`}
                  </p>
                  <Button 
                    onClick={handleGenerateSummary}
                    disabled={generatingSummary}
                    size="sm"
                  >
                    {generatingSummary ? (
                      <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    ) : (
                      <Sparkles className="h-4 w-4 mr-2" />
                    )}
                    生成AI总结
                  </Button>
                </div>

                {/* 总结内容 */}
                {summaries.length === 0 ? (
                  <div className="text-center py-12 text-muted-foreground">
                    <Sparkles className="h-12 w-12 mx-auto mb-4 opacity-50" />
                    <p>该日期还没有AI总结</p>
                    {entries.length > 0 && (
                      <Button 
                        onClick={handleGenerateSummary} 
                        variant="outline" 
                        className="mt-4"
                        disabled={generatingSummary}
                      >
                        生成今日总结
                      </Button>
                    )}
                  </div>
                ) : (
                  <div className="space-y-4">
                    {summaries.map((summary) => (
                      <Card key={summary.id} className="p-6">
                        <div className="flex items-center justify-between mb-4">
                          <h3 className="text-lg font-semibold">
                            {new Date(summary.date).toLocaleDateString('zh-CN')}
                          </h3>
                          <Badge variant="secondary">
                            {formatDateTimeToLocal(summary.created_at)}
                          </Badge>
                        </div>
                        
                        <div className="space-y-4">
                          <div>
                            <h4 className="font-medium mb-2">每日总结</h4>
                            <p className="text-gray-700 whitespace-pre-wrap">{summary.summary}</p>
                          </div>
                          
                          {summary.highlights.length > 0 && (
                            <div>
                              <h4 className="font-medium mb-2">今日亮点</h4>
                              <ul className="list-disc list-inside space-y-1">
                                {summary.highlights.map((highlight, index) => (
                                  <li key={index} className="text-gray-700">{highlight}</li>
                                ))}
                              </ul>
                            </div>
                          )}
                          
                          {summary.mood_analysis && (
                            <div>
                              <h4 className="font-medium mb-2">心情分析</h4>
                              <p className="text-gray-700">{summary.mood_analysis}</p>
                            </div>
                          )}
                        </div>
                      </Card>
                    ))}
                  </div>
                )}
              </div>
            </TabsContent>
          </Tabs>
        </div>
      </div>
    </div>
  );
}

